package com.zytech.zspider.task.impl.http;

import com.google.common.collect.Maps;
import com.zytech.modules.lang.Langs;
import com.zytech.modules.lang.Requires;

import java.util.Collections;
import java.util.Map;

/**
 * @author siuming
 */
public final class HttpTaskRequest {

    public enum Verb {
        GET, POST, PUT, DELETE
    }

    private final String url;
    private final Verb verb;

    private Map<String, String> headers = Maps.newHashMap();
    private Map<String, String> params = Maps.newHashMap();
    private String body;

    /**
     * @param url
     * @param verb
     */
    HttpTaskRequest(String url, Verb verb) {
        this.url = url;
        this.verb = verb;
    }

    /**
     * @return
     */
    public String getUrl() {
        return url;
    }

    /**
     * @return
     */
    public Verb getVerb() {
        return verb;
    }

    /**
     * @return
     */
    public Map<String, String> getHeaders() {
        return Collections.unmodifiableMap(headers);
    }

    /**
     * @param name
     * @param val
     * @return
     */
    public HttpTaskRequest header(String name, String val) {
        Requires.hasText(name, "name must not be null or empty.");
        this.headers.put(name, Langs.nullSafe(val, ""));
        return this;
    }

    /**
     * @param headers
     * @return
     */
    public HttpTaskRequest headers(Map<String, String> headers) {
        Requires.notNull(headers, "headers must not be null.");
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            header(entry.getKey(), entry.getValue());
        }
        return this;
    }

    /**
     * @return
     */
    public Map<String, String> getParams() {
        return Collections.unmodifiableMap(params);
    }

    /**
     * @param name
     * @param val
     * @return
     */
    public HttpTaskRequest param(String name, String val) {
        Requires.hasText(name, "name must not be null or empty.");
        this.params.put(name, Langs.nullSafe(val, ""));
        return this;
    }

    /**
     * @param params
     * @return
     */
    public HttpTaskRequest params(Map<String, String> params) {
        Requires.notNull(params, "params must not be null.");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            param(entry.getKey(), entry.getValue());
        }
        return this;
    }

    /**
     * @return
     */
    public String getBody() {
        return body;
    }

    /**
     * @param body
     * @return
     */
    public HttpTaskRequest body(String body) {
        this.body = body;
        return this;
    }

    /**
     * @param url
     * @param verb
     * @return
     */
    public static HttpTaskRequest of(String url, Verb verb) {
        Requires.hasText(url, "url must not be null.");
        Requires.notNull(verb, "verb must not be null.");
        return new HttpTaskRequest(url, verb);
    }
}
